package cn.yi.newsys.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.yi.newsys.dao.CommentDao;
import cn.yi.newsys.pojo.Comment;
import cn.yi.newsys.utils.BaseDao;

public class CommentDaoImpl extends BaseDao implements CommentDao{

	@Override
	public List<Comment> queryCommentByNewsID(int id , int offset , int pageSize) {
		String sql = "SELECT cid,cnid,ccontent,cdate,cip,cauthor FROM news_comments WHERE cnid=? ORDER BY cdate DESC LIMIT ?,?" ;
		// 创建 Comment 对象
		Comment com = null ;
		// 创建集合
		List<Comment> list = new ArrayList<Comment>() ;
		// 设置参数
		Object objs [] = new Object []{id,offset,pageSize} ;
		// 执行SQL语句
		ResultSet rs = this.executeQuery(sql, objs) ;
		try {
			while(rs != null && rs.next()){
				com = new Comment() ;
				// 赋值
				com.setCauthor(rs.getString("cauthor")) ;
				com.setCcontent(rs.getString("ccontent")) ;
				com.setCdate(rs.getDate("cdate")) ;
				com.setCid(rs.getInt("cid")) ;
				com.setCip(rs.getString("cip")) ;
				com.setCnid(rs.getInt("cnid")) ;
				// 将所得对象放入集合中
				list.add(com) ;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list ;
	}

	@Override
	public int save(Comment com) {
		String sql = "INSERT INTO news_comments(cnid,ccontent,cdate,cip,cauthor) VALUES(?,?,?,?,?)" ;
		// 设置参数
		Object objs[] = new Object[]{com.getCnid(),com.getCcontent(),com.getCdate(),com.getCip(),com.getCauthor()} ;
		int row = 0 ;
		try{
			// 执行 SQL 语句
			row = this.executeUpdate(sql, objs) ;	
		}finally{
			this.close() ;
		}
		return row ;
	}

	@Override
	public int getTotalComment(int nid) {
		String sql = "SELECT COUNT(*) FROM news_comments WHERE cnid=?" ;
		int total = 0 ;
		// 设置参数
		Object objs [] = new Object[]{nid} ;
		// 执行 SQL 语句
		ResultSet rs = this.executeQuery(sql, objs);
		try {
			if(rs != null && rs.next()){
				total = rs.getInt(1) ;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return total ;
	}

}
